/*
 * @Description: 用户聊天
 * @Author: fhw
 * @Date: 2022-08-05 11:32:48
 */
import {
  WebSocketGateway,
  SubscribeMessage,
  MessageBody,
  ConnectedSocket,
  WebSocketServer,
} from '@nestjs/websockets';
import { SocketFriendChatService } from './socket-friend-chat.service';
// import { Socket } from 'dgram'
import { isEmpty, isNil } from 'ramda';
import { ConfigService } from '../config/config.service';
import { SocketType, socketError, timestampToTime } from 'src/utlis';
import { UserChatRecord } from 'src/chat-record/entities/user-chat-record.entity';
import { HistorySessionService } from 'src/history-session/history-session.service';
import { ChatUserFriendsService } from 'src/chat_user_friends/chat_user_friends.service';
import { SocketRoomService } from '../socket-room/socket-room.service';

@WebSocketGateway({
  // 域名
  // namespace: '/flutter',
  // 解决跨域
  allowEIO3: true,
  cors: {
    origin: /.*/,
    credentials: true,
  },
})
export class SocketFriendChatGateway {
  constructor(
    private readonly socketFriendChatService: SocketFriendChatService,
    public readonly configService: ConfigService,
    // 历史会话
    private readonly socketRoomService: SocketRoomService,
    private readonly chatUserFriendsService: ChatUserFriendsService
  ) { }
  @WebSocketServer() server: any
  // 发送聊天
  @SubscribeMessage('sendChat')
  async sendChat(
    @MessageBody() params,
    @ConnectedSocket() clinet,
  ) {
    try {
      const data = await this.socketFriendChatService.sendChat(params) as UserChatRecord | SocketType;
      // 写入聊天记录报错返回报错信息
      if ((data as SocketType).success === false) {
        clinet.emit('socketError', data);
        return
      }
      // 更新好友最新消息
      await this.chatUserFriendsService.updateFriendsLatestNews({
        friendsId: params.to_userId,
        userId: params.userId
      }, data as UserChatRecord)
      // await this.historySessionService.updateLatestNews({
      //   historicalUserSessionsId: params.to_userId,
      //   userId: params.userId
      // }, data as UserChatRecord)
      await this.getChatUnreadRecord(params.to_userId)
      clinet
        .to(this.configService.getChatUser(String((data as UserChatRecord)?.to_userId)))
        .emit('acceptChat', data);
    } catch (error) {
      console.log(error.magess);
    }

  }
  // 更新未读消息
  @SubscribeMessage('updateUnreadMessage')
  async updateUnreadMessage(
    @MessageBody() params,
    @ConnectedSocket() clinet,
  ) {
    const { ids, userId, group_id } = params
    if (isNil(group_id)) {
      if (isNil(ids)) {
        return clinet.emit('socketError', socketError('聊天消息ID集合不存在'));
      };
      if (isEmpty(ids)) {
        this.getChatUnreadRecord(userId)
        return
      }
      const { success, msg } = await this.socketFriendChatService.setUserChatRead(ids);
      if (!success) {
        clinet.emit('socketError', { code: 500, message: msg });
      } else {
        this.getChatUnreadRecord(userId)
      }
    } else if (group_id) {
      const { success, msg } = await this.socketRoomService.setGroupChatRead(group_id, userId);
      if (!success) {
        clinet.emit('socketError', { code: 500, message: msg });
      } else {
        this.getChatUnreadRecord(userId)
      }
    }

  }
  // 获取未读消息记录
  @SubscribeMessage('unread')
  async getChatUnreadRecord(@MessageBody() userId) {
    const chatUnreadRecord = await this.socketFriendChatService.getChatUnreadRecord(userId)
    const groupUnreadRecord = await this.socketRoomService.getGroupUnreadRecord(userId)
    this.server.in(this.configService.getChatUser(String(userId))).emit('unread', Object.assign(chatUnreadRecord, groupUnreadRecord));
  }
}
